package logic

import (
	"context"
	"errors"
	"strconv"
	"taobao-merchandise/mysql"
	"taobao-merchandise/pkg"

	"taobao-merchandise/taobaorpc/internal/svc"
	"taobao-merchandise/taobaorpc/taobaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *taobaorpc.LoginRequest) (*taobaorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	err := user.Login(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("用户不存在,请注册")
	}
	if user.Password != in.Password {
		return nil, errors.New("密码错误,请重新输入")
	}

	handler, err := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	if err != nil {
		return nil, err
	}

	return &taobaorpc.LoginResponse{
		Token: handler,
	}, nil
}
